#!/usr/bin/perl -w
use strict;
use utf8;

use IO::HTML;
use HTML::TreeBuilder;
use HTML::Element;
use List::MoreUtils qw(any);
use Data::Dumper;

my @filters = (
    sub {
        my $e = shift;
        if ( $e->tag eq 'link' && $e->attr('href')){
            if($e->attr('href') =~ m/^(http:)?\/\/fonts\.googleapis\.com\/.*/) {
                print "link element to fonts.googleapis.com is found.\n";
                return 1;
            } elsif ($e->attr('href') =~ m/^http:\/\/developer\.android\.com\/.*/){
                print "link element to developer.android.com is found.\n";
                return 1;
            }
        }
        0;
    },
    sub {
        my $e = shift;
        if ( $e->tag eq 'script' && $e->attr('src') && $e->attr('src') =~ m/^http:\/\/www\.google\.com\/.*/) {
            print "script element to $& is found.\n";
            return 1;
        }
        0;
    },
    sub {
        my $e = shift;
        if ( $e->tag eq 'script' && $e->attr('src') && $e->attr('src') eq 'https://developer.android.com/ytblogger_lists_unified.js') {
            print "script element to ytblogger_lists_unified.js is found.\n";
            return 1;
        }
        0;
    },
    sub {
        my $e = shift;
        my @contents = $e->content_list;
        return 0 if $e->tag ne 'script';
        if ($contents[0] && $contents[0] =~ m/.*\.google-analytics\.com\/.*/) {
            print "script element to google-analytics.com is found.\n";
            return 1;
        }
        0;
    }
    );

foreach my $file (@ARGV) {
    my $root = HTML::TreeBuilder->new_from_file(html_file($file));
    my @todo = $root->content_list;
    while (@todo) {
        my $elem = shift @todo;
        if (any {$_->($elem)} @filters) {
            #      print $elem->as_HTML,"\n";
            $elem->delete;
            next;
        }
        unshift @todo, grep ref $_,$elem->content_list;
    }

    open CLEAN_HTML, ">${file}.clean";
    print CLEAN_HTML $root->as_HTML;
    close CLEAN_HTML;
    unlink $file or warn "Could not unlink $file.";
    rename "${file}.clean",$file;
}
